var consumer = {};

consumer.igooglereader =
{ consumerKey   : "jQfyGDajSDrlgpDXcOOxg"
, consumerSecret: "4A084ppD6v3ZS4xy2OWbcAF6rdH84Idu4LRrakf830"
, serviceProvider:
  { signatureMethod     : "HMAC-SHA1"
  , requestTokenURL     : "https://api.twitter.com/oauth/request_token"
  , userAuthorizationURL: "https://api.twitter.com/oauth/authorize"
  , accessTokenURL      : "https://api.twitter.com/oauth/access_token"
  }
};

var c = consumer.igooglereader;

function doLogin() {
	getRequestToken(c);
}

/* Request Token */
function getRequestToken() {
    sendRequest( { method: 'POST'
                 , action: c.serviceProvider.requestTokenURL
                 , parameters: { oauth_signature_method: c.serviceProvider.signatureMethod
                               , oauth_consumer_key: c.consumerKey
                               }
                 }
               , { consumerSecret: c.consumerSecret
                 , tokenSecret   : ''
                 }
               , getResponseToken
               );
};
function getResponseToken(response) {
	var responseText = response['text'];
	var token = responseText.substring(responseText.indexOf('oauth_token=') + 12, responseText.indexOf('&'));
	var secret = responseText.substring(responseText.indexOf('oauth_token_secret=') + 19);
	authorizeApp(responseText);
}

function authorizeApp(token) {
	var accessTokenHref = c.serviceProvider.userAuthorizationURL + '?' + token;
	window.open(accessTokenHref);
}

/* Access Token */
function getAccessToken(token) {
	sendRequest( { method: 'GET'
                 , action: c.serviceProvider.accessTokenURL
                 , parameters: { oauth_signature_method: c.serviceProvider.signatureMethod
                               , oauth_consumer_key: c.consumerKey
                               , oauth_token: token
                               }
                 }
               , { consumerSecret: c.consumerSecret
                 , tokenSecret   : ''
                 }
               , getResponseAccessToken
               );
};
function getResponseAccessToken(response) {
	alert(response);
	showObject(response);
}

/* Access Token Secret */
function getAccessTokenSecret(token, secret) {
	sendRequest( { method: 'GET'
                 , action: c.serviceProvider.accessTokenURL
                 , parameters: { oauth_signature_method: c.serviceProvider.signatureMethod
                               , oauth_consumer_key: c.consumerKey
                               , oauth_token: token
                               }
                 }
               , { consumerSecret: c.consumerSecret
                 , tokenSecret   : secret
                 }
               , getResponseAccessTokenSecret
               );
};
function getResponseAccessTokenSecret(response) {
	showObject(response);
	showObject(response.errors);
    showObject(response.headers);
}

/* sendRequest */
function sendRequest(message, accessor, callbackFunction) {
    OAuth.setTimestampAndNonce(message);
    OAuth.SignatureMethod.sign(message, accessor);
    var method = METHOD_TYPES[message.method];
    var URL = message.action;
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = method;
    if (method == gadgets.io.MethodType.POST) {
        params[gadgets.io.RequestParameters.HEADERS] = {'Content-Type': 'application/x-www-form-urlencoded'};
        params[gadgets.io.RequestParameters.POST_DATA] = OAuth.formEncode(message.parameters);
    } else {
        URL = OAuth.addToURL(URL, message.parameters);
        // This would be better, but you can't get the headers from the response.
        // params[gadgets.io.RequestParameters.HEADERS]
        // = {Authorization: OAuth.getAuthorizationHeader(message.parameters)};
    }
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    gadgets.io.makeRequest(URL, callbackFunction, params);

    // var client = new XMLHttpRequest();
    // client.onreadystatechange = handler;
    // This will fail, indicating 'Access Denied':
    // client.open(message.method, message.action);
    // client.send();
    // I suppose the implementation of XMLHttpRequest is
    // provided by the browser, which restricts access.
};

function showResponse(response) {
    showObject(response);
    showObject(response.errors);
    showObject(response.headers);
};
function showObject(thing) {
    if (thing != null) {
        var msg = "";
        for (var t in thing) {
            if (thing[t] !== undefined) {
                msg += (t + ": " + thing[t] + "\n");
            }
        }
        if (msg != "") {
            alert(msg);
        }
    }
};
var METHOD_TYPES = { 'GET'   : gadgets.io.MethodType.GET
                   , 'POST'  : gadgets.io.MethodType.POST
                   , 'PUT'   : gadgets.io.MethodType.PUT
                   , 'DELETE': gadgets.io.MethodType.DELETE
                   };